@extends('wx.layout.default')

@section('wx.pheader')
  @include('wx.layout.swiper')
@stop

@section('wx.pbody')

<form class="form-horizontal" id="wx-clase" autocomplete="off" enctype="multipart/form-data">
  <div class="weui-form">
    @if(empty($deploy))
    <div class="weui-form__text-area">
      <h2 class="weui-form__title">{{$type->desc}}在线报名</h2>
      <div class="weui-form__desc" style="padding-bottom: 56px;">
          请关注我们的公众号，及时获取报名信息！
      </div>
      <div class="weui-form__control-area"></div>
      <div class="weui-form__opr-area">
        <a href="/" class="weui-btn weui-btn_default">返回</a>
      </div>
    </div>
    @else
    <div class="weui-form__text-area">
      <h2 class="weui-form__title">{{$deploy->name}}在线报名</h2>
      <div class="weui-form__desc" style="text-align: left;font-size: 16px;">
        {{$deploy->desc}}
      </div>
    </div>
    <div class="weui-form__control-area">

      {{ csrf_field() }}
      <input type="hidden" name="uid" value="{{$user->id}}"/>


        <div class="weui-cells__group weui-cells__group_form">
          <div class="weui-cells__title b">
            {{ $deploy->term->name}} ({{ $deploy->branch->name}})
            @if($deploy->limit > 0)
            【每人限报{{$deploy->limit}}门】
            @endif
          </div>
          <div class="weui-cells weui-cells_radio deploys">
            @foreach($deploy->infos as $info)
            @if(!!$info->clase->images)
            <img src="{{$info->clase->images}}" width="100%"/>
            @endif
            <label class="weui-cell weui-cell_active weui-check__label" for="clase{{$info->clase->id}}">
                <div class="weui-cell__bd">
                    <p>【{{$info->clase->category->name}}】{{$info->clase->name}}</p>
                    <ul class="weui-media-box__info">
                        @if($info->clase->is_exam)
                        <li class="weui-media-box__info__meta"><span class="weui-badge" style="border-radius: 4px;background-color: var(--weui-FG-1)">{!! $info->clase->present()->isExam('label') !!}</span></li>
                        @endif

                        @if($info->clase->is_limited)
                        <li class="weui-media-box__info__meta" style="width: 100%;"><span class="weui-badge" style="border-radius: 4px;background-color: var(--weui-FG-1)">{!! $info->clase->present()->isLimited('label') !!}</span> <span style="float:right;color:var(--weui-FG-1);"> 已报名:<span style="color:var(--weui-BRAND);font-weight: 700">{{count($info->clase->enrolled)}}</span>  剩余:<span style="color:var(--weui-RED);font-weight: 700">{{$info->clase->number-count($info->clase->enrolled)}}</span></span></li>
                        @endif

                        @if($info->clase->is_handin)
                        <li class="weui-media-box__info__meta"><span class="weui-badge" style="border-radius: 4px;background-color: var(--weui-FG-1)">{!! $info->clase->present()->isHandin('label') !!}</span></li>
                        @endif
                    </ul>
                    <p class="weui-media-box__desc" style="-webkit-line-clamp: 6 !important;">
                      {{$info->clase->content}}
                    </p>
                    <p class="weui-media-box__desc" style="color:var(--weui-ORANGE)">时间：{{$info->clase->classtime}}</p>
                </div>
                <div class="weui-cell__ft">
                    <input type="radio" class="weui-check" name="clase" id="clase{{$info->clase->id}}"
                    value="{{$info->clase->id}}" data-deploy="{{$deploy->id}}" data-handin="{{$info->clase->is_handin}}">
                    <span class="weui-icon-checked"></span>
                </div>
            </label>

            @endforeach
          </div>

        </div>


      <div class="weui-cell weui-cell_uploader uploader" style="display: none;">
          <div class="weui-cell__bd">
              <div class="weui-uploader">
                  <div class="weui-uploader__hd">
                      <p class="weui-uploader__title">附件上传</p>
                      <div class="weui-uploader__info"><span id="uploadCount">0</span>/4</div>
                  </div>
                  <div class="weui-uploader__bd">
                      <ul class="weui-uploader__files" id="uploaderFiles"></ul>
                      <div class="weui-uploader__input-box">
                          <input class="weui-uploader__input" id="uploaderInput" name="files" type="file" accept="image/*" multiple="multiple">
                      </div>
                  </div>
              </div>
          </div>
      </div>

      <div class="weui-gallery" id="gallery">
        <span class="weui-gallery__img" id="galleryImg"></span>
        <div class="weui-gallery__opr">
            <a href="javascript:" class="weui-gallery__del">
                <i class="weui-icon-delete weui-icon_gallery-delete"></i>
            </a>
        </div>
    </div>

    </div>


    <div class="weui-form__opr-area">
      <button class="weui-btn weui-btn_primary" id="btnDeploy">我要报名</button>
    </div>
    @endif


  </div>
</form>
@stop

@section('javascript')
  <script src="//cdn.bootcss.com/jquery-validate/1.19.1/jquery.validate.min.js"></script>
  <script src="{{URL::asset('/assets/js/jquery-validate-methods.js')}}"></script>
  <script src="//cdn.bootcss.com/jqueryui/1.12.1/jquery-ui.min.js"></script>
  <script src="//cdn.bootcss.com/jquery-weui/1.2.1/js/swiper.min.js"></script>
  <script type="text/javascript" src="//res.wx.qq.com/open/libs/weuijs/1.2.1/weui.min.js"></script>
  <script type="text/javascript">


  $(function () {

      var ishadin = 0;

      $('input:radio[name="clase"]').on('click', function () {
          var that = $(this);

          $('.uploader').hide();

          ishandin = that.data('handin');
          ischeck = that.is(':checked');

          if( ishandin && ischeck){
                $("#uploaderInput").rules("add", {
                    required : true,
                    messages : {
                        required : "请上传作品或公益证书"
                    }
                });
            $('.uploader').show();
          }
          else{
            $("#uploaderInput").rules("remove");
          }

      });



      $("#wx-clase").validate({
          onfocusout: false,
          onkeyup: false,
          rules: {
              clase: {required: true},
          },
          messages: {
              clase: {required: "请选择需要报名的课程"},
          },

          showErrors: function (errorMap, errorList) {
              $.each(errorList, function (i, v) {
                  layer.msg(v.message, {shift: -1, time: 2000});
                  return false;
              });
          },

          submitHandler: function (form) {

              var formData = new FormData();
              formData.append('_token', $("input[name='_token']").attr('value') );
              formData.append('clase', $("input[name='clase']:checked").val() );
              formData.append('deploy', $("input[name='clase']:checked").data('deploy') );
              formData.append('uid', $("input[name='uid']").val() );
              formData.append('source', 1 );
              formData.append('ishandin', ishandin );
              for (var i = 0; i < uploadFileList.length; i++){
                formData.append("files[]",uploadFileList[i])
              }

              $.ajax({
                type: "post",
                dataType: 'json',
                url: "{{route('wx.sign')}}",
                data: formData,
                processData: false,
                contentType: false,
                success: function(data) {
                  console.log(data)
                  layer.msg(data.message, {time: 1000,shift: -1}, function () {
                      if (data.status === true && data.url != null) {

                          $(window).attr('location', data.url);

                      }
                  });
                },
                error: function (data) {
                    layer.msg(data.responseJSON.message);
                }
              });

          }

      });

      var uploadFileList = [];

      var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];
      var maxSize = 1024 * 1024*10; // 10240KB，也就是 10MB
      var maxWidth = 1900;  // 图片最大宽度
      var maxCount = 4;// 最大上传图片数量
      var tmpl = '<li class="weui-uploader__file weui-uploader__file_status" id="#ImgID#" style="background-image:url(#url#)"><div class="weui-uploader__file-content"><i class="weui-loading" style="width:30px;height:30px"></i></div></li>',
          $gallery = $("#gallery"),
          $galleryImg = $("#galleryImg"),
          $uploaderInput =   $("#uploaderInput"),
          $uploaderFiles = $("#uploaderFiles");

      $uploaderInput.on("change", function (e) {
            files = e.target.files;
            // 如果没有选中文件，直接返回
            if (files.length === 0) {
                return;
            }
            for (var i = 0, len = files.length; i < len; ++i) {
                var file = files[i];
                var imgID = genGUID();
                var reader = new FileReader();
                var fileType = file.type;
                // 如果类型不在允许的类型范围内
                if (allowTypes.indexOf(file.type) === -1) {
                    layer.msg('该类型不允许上传' + fileType);
                    continue;
                }

                if (file.size > maxSize) {
                    layer.msg("图片太大，不允许上传");
                    continue;
                }

                if ($('.weui-uploader__file').length >= maxCount) {
                    layer.msg('最多只能上传' + maxCount + '张图片');
                    return;
                }

                uploadFileList.push(file);

                reader.onload = function (e) {
                    var img = new Image();
                    img.onload = function () {
                        // 不要超出最大宽度
                        var w = Math.min(maxWidth, img.width);
                        // 高度按比例计算
                        var h = img.height * (w / img.width);
                        var canvas = document.createElement('canvas');
                        var ctx = canvas.getContext('2d');
                        // 设置 canvas 的宽度和高度
                        canvas.width = w;
                        canvas.height = h;
                        ctx.drawImage(img, 0, 0, w, h);
                        var base64 = canvas.toDataURL(fileType,0.6); //0.6指的是压缩60%

                        // 插入到预览区
                        $uploaderFiles.append($(tmpl.replace('#url#', base64).replace('#ImgID#', imgID)));

                        var num = $('.weui-uploader__file').length;
                        $('#uploadCount').text(num);

                        function uploading() {

                            $uploaderFiles.find('.weui-uploader__file').removeClass('weui-uploader__file_status');
                            $uploaderFiles.find('.weui-uploader__file-content').remove();//清除上传进度图标
                        }
                        setTimeout(uploading, 1000);
                    };

                    img.src = e.target.result;


                };
                reader.readAsDataURL(file);

            }
        });

      var index; //第几张图片
        $uploaderFiles.on("click", "li", function () {
            index = $(this).index();
            $galleryImg.attr("style", this.getAttribute("style"));
            $gallery.fadeIn(100);
        });
        $gallery.on("click", function () {
            $gallery.fadeOut(100);
        });

        //删除图片
        $(".weui-gallery__del").click(function () {
            $uploaderFiles.find("li").eq(index).remove();
            uploadFileList.splice(index,1);
            var num = $('.weui-uploader__file').length;
            $('#uploadCount').text(num);
        });

      function genGUID() {
        var G1 = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        var G2 = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        return (G1 + G2);
    }


      $('.swiper-container').swiper({
        loop: true,
        autoplay: 5000,
        pagination: '.swiper-pagination',
        paginationClickable: true
      });


  });
  </script>
@stop